package spil;

import desktop_resources.GUI;

public class Game {
	static int loseCount = 0;
	static Player[] players;
	static Dice d1 = new Dice();
	static GameBoard board = new GameBoard();

	public static void main(String[] args) {
		initiate();
		while(true) {
			for(int i = 0; i < players.length; i++) {
				if(!players[i].hasLost())
					playerTurn(players[i]);
				for(int j = 0; j < players.length; j++)
					GUI.setBalance("" + players[i].getNumber(), players[i].getBalance());
			}
			if (loseCount == players.length - 1)
				break;
		}
		int winner = checkWinner();
		GUI.getUserButtonPressed(players[winner]+" has won.\nWell done", "ok");
	}

	public static void initiate() {
		board.setFields();
		int pnumber = GUI.getUserInteger("How many players", 2, 6);
		players = new Player[pnumber];
		for(int i = 0; i < pnumber; i++) {
			players[i] = new Player(i+1);
			GUI.addPlayer(""+(i+1), 0);
			GUI.setCar(1, ""+(i+1));
			GUI.setBalance("" + (i+1), players[i].getBalance());
		}
	}

	public static void playerTurn(Player p) {
		d1.roll();
		p.move(d1.getSum());
		GUI.setDice(d1.getd1(), d1.getd2());
		board.getField(p.getFelt()).landOnField(p);
		if(p.getBalance() <= 0) {
			loseCount++;
			p.lose();
			loseProperty(p);
			p.account.setBalance(0);
			GUI.removeCar(p.getFelt(), "" + p.getNumber());
		}
	}

	public static void loseProperty(Player p) {
		for(int i = 0; i < board.getOwnables().length; i++) {
			for(int j = 0; j < board.getOwnables()[i].length; j++) {
				board.getOwnables()[i][j].lose(p);
			}
		}
	}

	public static int checkWinner() {
		for(int i = 0; i < players.length; i++) {
			if(!players[i].hasLost())
				return i;
		}
		return 0;
	}
}